﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


using agsXMPP;
using agsXMPP.protocol.client;
using agsXMPP.Collections;
	
namespace jabberclient1
{
	/// <summary>
	/// Interaction logic for ChatWindow.xaml
	/// </summary>
	public partial class ChatWindow : Window
	{
		Jid _jid;
		XmppClientConnection _myclient;
		Boolean privateChat=true;
			
		public ChatWindow(Jid jid, XmppClientConnection myclient)
		{
			this.InitializeComponent();
			_jid=jid;
			_myclient=myclient;
			
		   Util.ChatForms.Add(jid.Bare.ToLower(),this);
			
			
			
			// Setup new Message Callback
            if (privateChat)
                _myclient.MessageGrabber.Add(jid, new BareJidComparer(), new MessageCB(MessageCallback), null);
            else
                _myclient.MessageGrabber.Add(jid, new FullJidComparer(), new MessageCB(MessageCallback), null);
       
		}

		private void OutgoingMessage(agsXMPP.protocol.client.Message msg)
		{
			//MessageBox.Show("hi");
			
			rtfChat.AppendText(msg.To.Bare+":");
			rtfChat.AppendText(msg.Body);
			rtfChat.AppendText("\r\n");
		}
		
		public void IncomingMessage(agsXMPP.protocol.client.Message msg)
		{
			
			rtfChat.AppendText(msg.To.Bare+":");
			rtfChat.AppendText(msg.Body);
			rtfChat.AppendText("\r\n");
		}
		private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			agsXMPP.protocol.client.Message msg = new agsXMPP.protocol.client.Message();

			msg.Type	= MessageType.chat;
			msg.To		= _jid;
			msg.Body	= txtchat.Text;
			
			_myclient.Send(msg);
			OutgoingMessage(msg);
			txtchat.Text="";
		}
		private void MessageCallback(object sender, agsXMPP.protocol.client.Message msg, object data)
		{
            if (this.rtfChat.Dispatcher.Thread!=System.Threading.Thread.CurrentThread)
			{
				rtfChat.Dispatcher.Invoke(new MessageCB(MessageCallback), new object[] { sender, msg, data });
                return;
            }
            //MessageBox.Show("...");
            if (msg.Body != null)
			    IncomingMessage(msg);
		}

		private void Window_Closed(object sender, System.EventArgs e)
		{
			Util.ChatForms.Remove(_jid.Bare.ToLower());
			
		}
	}
}